<template>
  <div class="order-detail-container">
    <!-- 返回按钮 -->
    <el-card class="back-card" shadow="never">
      <el-button @click="handleBack">
        <IconifyIconOffline icon="ep:arrow-left" class="mr-1" />
        返回订单列表
      </el-button>
    </el-card>

    <!-- 订单基本信息 -->
    <el-card v-if="orderDetail" class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">订单信息</span>
          <el-tag :type="getStatusColor(orderDetail.status)" size="large">
            {{ getStatusText(orderDetail.status) }}
          </el-tag>
        </div>
      </template>

      <el-descriptions :column="3" border>
        <el-descriptions-item label="订单号" :span="2">
          <el-text type="primary" size="large" tag="b">
            {{ orderDetail.orderNumber }}
          </el-text>
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusColor(orderDetail.status)">
            {{ getStatusText(orderDetail.status) }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="订单金额">
          <el-text type="danger" size="large" tag="b">
            ¥{{ orderDetail.amount.toFixed(2) }}
          </el-text>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          <div v-if="orderDetail.paymentMethod" class="payment-method">
            <IconifyIconOffline
              :icon="getPaymentIcon(orderDetail.paymentMethod)"
              class="payment-icon"
            />
            {{ getPaymentText(orderDetail.paymentMethod) }}
          </div>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="支付流水号">
          {{ orderDetail.transactionId || "-" }}
        </el-descriptions-item>

        <el-descriptions-item label="创建时间">
          {{ formatDateTime(orderDetail.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">
          {{ orderDetail.payTime ? formatDateTime(orderDetail.payTime) : "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="完成时间">
          {{
            orderDetail.finishTime
              ? formatDateTime(orderDetail.finishTime)
              : "-"
          }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 用户信息 -->
    <el-card v-if="orderDetail" class="user-card" shadow="never">
      <template #header>
        <span class="card-title">用户信息</span>
      </template>

      <div class="user-info">
        <el-avatar :size="60" :src="orderDetail.user.avatar">
          <IconifyIconOffline icon="ep:user" />
        </el-avatar>
        <div class="user-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">
              {{ orderDetail.user.username }}
            </el-descriptions-item>
            <el-descriptions-item label="真实姓名">
              {{ orderDetail.user.realName || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ orderDetail.user.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ orderDetail.user.email || "-" }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 商品信息 -->
    <el-card v-if="orderDetail" class="product-card" shadow="never">
      <template #header>
        <span class="card-title">商品信息</span>
      </template>

      <div class="product-info">
        <img :src="orderDetail.product.image" class="product-image" />
        <div class="product-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商品名称" :span="2">
              <el-text size="large" tag="b">
                {{ orderDetail.product.name }}
              </el-text>
            </el-descriptions-item>
            <el-descriptions-item label="商品类型">
              <el-tag type="info">
                {{ getProductTypeText(orderDetail.product.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="商品价格">
              <el-text type="danger" tag="b">
                ¥{{ orderDetail.product.price.toFixed(2) }}
              </el-text>
            </el-descriptions-item>
            <el-descriptions-item label="购买数量">
              {{ orderDetail.quantity }}
            </el-descriptions-item>
            <el-descriptions-item label="小计金额">
              <el-text type="danger" tag="b">
                ¥{{
                  (orderDetail.product.price * orderDetail.quantity).toFixed(2)
                }}
              </el-text>
            </el-descriptions-item>
            <el-descriptions-item label="商品描述" :span="2">
              {{ orderDetail.product.description || "-" }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 订单操作记录 -->
    <el-card class="log-card" shadow="never">
      <template #header>
        <span class="card-title">操作记录</span>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="log in operationLogs"
          :key="log.id"
          :timestamp="formatDateTime(log.createTime)"
          :type="getLogType(log.type)"
        >
          <div class="log-content">
            <div class="log-title">{{ log.title }}</div>
            <div class="log-description">{{ log.description }}</div>
            <div class="log-operator">操作人：{{ log.operator }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 操作按钮 -->
    <el-card v-if="orderDetail" class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handlePrint">
          <IconifyIconOffline icon="ep:printer" class="mr-1" />
          打印订单
        </el-button>

        <el-button
          v-if="orderDetail.status === 'paid'"
          type="warning"
          @click="handleRefund"
        >
          <IconifyIconOffline icon="ep:money" class="mr-1" />
          申请退款
        </el-button>

        <el-button
          v-if="orderDetail.status === 'pending'"
          type="danger"
          @click="handleCancel"
        >
          <IconifyIconOffline icon="ep:close" class="mr-1" />
          取消订单
        </el-button>

        <el-button
          v-if="orderDetail.status === 'paid'"
          type="success"
          @click="handleConfirm"
        >
          <IconifyIconOffline icon="ep:check" class="mr-1" />
          确认完成
        </el-button>
      </div>
    </el-card>

    <!-- 退款弹窗 -->
    <el-dialog v-model="refundVisible" title="申请退款" width="500px">
      <div v-if="orderDetail" class="refund-form">
        <el-form :model="refundForm" label-width="100px">
          <el-form-item label="订单号">
            <el-input v-model="orderDetail.orderNumber" disabled />
          </el-form-item>

          <el-form-item label="订单金额">
            <el-input v-model="orderDetail.amount" disabled>
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>

          <el-form-item label="退款金额">
            <el-input-number
              v-model="refundForm.amount"
              :min="0"
              :max="orderDetail.amount"
              :precision="2"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="退款原因">
            <el-select
              v-model="refundForm.reason"
              placeholder="选择退款原因"
              style="width: 100%"
            >
              <el-option label="用户申请退款" value="user_request" />
              <el-option label="活动取消" value="event_cancelled" />
              <el-option label="系统错误" value="system_error" />
              <el-option label="重复支付" value="duplicate_payment" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item label="退款说明">
            <el-input
              v-model="refundForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入退款说明"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="refundVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitRefund"
          >确认退款</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(false);
const refundVisible = ref(false);
const orderDetail = ref(null);

// 退款表单
const refundForm = reactive({
  amount: 0,
  reason: "",
  remark: ""
});

// 操作日志数据
const operationLogs = ref([
  {
    id: 1,
    type: "create",
    title: "订单创建",
    description: "用户创建订单，等待支付",
    operator: "系统",
    createTime: "2024-01-15 10:30:00"
  },
  {
    id: 2,
    type: "pay",
    title: "订单支付",
    description: "用户通过微信支付完成订单支付",
    operator: "张三",
    createTime: "2024-01-15 10:32:15"
  },
  {
    id: 3,
    type: "confirm",
    title: "订单确认",
    description: "管理员确认订单，订单处理完成",
    operator: "管理员",
    createTime: "2024-01-15 11:00:00"
  }
]);

// 模拟订单详情数据
const mockOrderDetail = {
  id: 1,
  orderNumber: "ORD202401150001",
  user: {
    id: 1,
    username: "张三",
    realName: "张三",
    phone: "13800138001",
    email: "zhangsan@example.com",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=male%20user%20avatar&image_size=square"
  },
  product: {
    id: 1,
    name: "春季篮球赛报名费",
    type: "activity",
    price: 50.0,
    description: "2024年春季篮球赛报名费用，包含比赛服装和纪念品",
    image:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=basketball%20tournament%20poster&image_size=square"
  },
  quantity: 1,
  amount: 50.0,
  status: "paid",
  paymentMethod: "wechat",
  transactionId: "WX20240115103215001",
  createTime: "2024-01-15 10:30:00",
  payTime: "2024-01-15 10:32:15",
  finishTime: "2024-01-15 11:00:00",
  remark: "用户正常报名支付"
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm:ss");
};

// 获取订单状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待支付",
    paid: "已支付",
    cancelled: "已取消",
    refunded: "已退款",
    failed: "支付失败",
    completed: "已完成"
  };
  return statusMap[status] || status;
};

// 获取订单状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: "warning",
    paid: "success",
    cancelled: "info",
    refunded: "danger",
    failed: "danger",
    completed: "primary"
  };
  return colorMap[status] || "info";
};

// 获取商品类型文本
const getProductTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    activity: "活动报名",
    membership: "会员费",
    training: "培训课程",
    match: "比赛报名",
    equipment: "器材购买"
  };
  return typeMap[type] || type;
};

// 获取支付方式文本
const getPaymentText = (method: string) => {
  const methodMap: Record<string, string> = {
    wechat: "微信支付",
    alipay: "支付宝",
    bank: "银行卡",
    balance: "余额支付"
  };
  return methodMap[method] || method;
};

// 获取支付方式图标
const getPaymentIcon = (method: string) => {
  const iconMap: Record<string, string> = {
    wechat: "ri:wechat-pay-line",
    alipay: "ri:alipay-line",
    bank: "ep:credit-card",
    balance: "ep:wallet"
  };
  return iconMap[method] || "ep:money";
};

// 获取日志类型
const getLogType = (type: string) => {
  const typeMap: Record<string, string> = {
    create: "primary",
    pay: "success",
    cancel: "warning",
    refund: "danger",
    confirm: "success"
  };
  return typeMap[type] || "primary";
};

// 返回列表
const handleBack = () => {
  router.push("/order/list");
};

// 打印订单
const handlePrint = () => {
  window.print();
};

// 申请退款
const handleRefund = () => {
  if (orderDetail.value) {
    refundForm.amount = orderDetail.value.amount;
    refundForm.reason = "";
    refundForm.remark = "";
    refundVisible.value = true;
  }
};

// 取消订单
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 "${orderDetail.value?.orderNumber}" 吗？`,
      "确认取消",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    if (orderDetail.value) {
      orderDetail.value.status = "cancelled";
    }
    ElMessage.success("订单已取消");
  } catch {
    // 用户取消
  }
};

// 确认完成
const handleConfirm = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要确认完成订单 "${orderDetail.value?.orderNumber}" 吗？`,
      "确认完成",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }
    );

    if (orderDetail.value) {
      orderDetail.value.status = "completed";
    }
    ElMessage.success("订单已完成");
  } catch {
    // 用户取消
  }
};

// 提交退款
const handleSubmitRefund = () => {
  if (!refundForm.reason) {
    ElMessage.warning("请选择退款原因");
    return;
  }

  if (refundForm.amount <= 0) {
    ElMessage.warning("退款金额必须大于0");
    return;
  }

  if (orderDetail.value) {
    orderDetail.value.status = "refunded";
  }

  ElMessage.success("退款申请已提交");
  refundVisible.value = false;
};

// 加载订单详情
const loadOrderDetail = async () => {
  loading.value = true;
  try {
    const orderId = route.params.id;
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    orderDetail.value = mockOrderDetail;
  } catch (error) {
    ElMessage.error("加载订单详情失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadOrderDetail();
});
</script>

<style scoped lang="scss">
.order-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.back-card,
.info-card,
.user-card,
.product-card,
.log-card,
.action-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.user-info {
  display: flex;
  gap: 20px;
  align-items: flex-start;

  .user-detail {
    flex: 1;
  }
}

.product-info {
  display: flex;
  gap: 20px;
  align-items: flex-start;

  .product-image {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    object-fit: cover;
    border: 1px solid #ebeef5;
  }

  .product-detail {
    flex: 1;
  }
}

.payment-method {
  display: flex;
  align-items: center;
  gap: 4px;

  .payment-icon {
    font-size: 16px;
  }
}

.log-content {
  .log-title {
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }

  .log-description {
    color: #606266;
    margin-bottom: 4px;
  }

  .log-operator {
    font-size: 12px;
    color: #909399;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.refund-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .order-detail-container {
    padding: 10px;
  }

  .user-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .product-info {
    flex-direction: column;
    align-items: center;
    text-align: center;

    .product-image {
      width: 100px;
      height: 100px;
    }
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
}

@media print {
  .back-card,
  .action-card {
    display: none;
  }

  .order-detail-container {
    padding: 0;
    background-color: white;
  }

  .info-card,
  .user-card,
  .product-card,
  .log-card {
    box-shadow: none;
    border: 1px solid #ddd;
    margin-bottom: 10px;
  }
}
</style>
